from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_cors import CORS
from config import Config

db = SQLAlchemy()
login_manager = LoginManager()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    CORS(app)

    from app.routes import auth, objectives, projects, status, query, admin
    app.register_blueprint(auth.bp)
    app.register_blueprint(objectives.bp)
    app.register_blueprint(projects.bp)
    app.register_blueprint(status.bp)
    app.register_blueprint(query.bp)
    app.register_blueprint(admin.bp)

    # 根路径路由
    @app.route('/')
    def index():
        from flask import redirect, url_for
        from flask_login import current_user
        if current_user.is_authenticated:
            return redirect(url_for('auth.dashboard'))
        return redirect(url_for('auth.login'))

    with app.app_context():
        db.create_all()

    return app